package rbb.itm5.bwinf.roboter.View;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.text.MaskFormatter;
import rbb.itm5.bwinf.roboter.Control.ControlerEvents;
import rbb.itm5.bwinf.roboter.Control.DriverInterface;

public class ControlPanel implements ActionListener {

    private JPanel view;
    private JLabel steps = new JLabel("0 Schritte"), driver = new JLabel("Fahrer: "), roomLabel = new JLabel("Raum:"), driverLabel = new JLabel("Fahrer:"), timeLabel = new JLabel("Intervall:");
    private JLabel runTime = new JLabel("Zeit: 0 ms");
    private ControlerEvents event;
    private JComboBox roomBox = new JComboBox(), driverBox = new JComboBox();
    private JButton load = new JButton("load"), play = new JButton(), pause = new JButton(), stop = new JButton(), minus = new JButton(), plus = new JButton();
    private JCheckBox paintSteps = new JCheckBox("Zeichne Schritte"), paintObstacles = new JCheckBox("Zeichne Hindenisse");
    private JTextField time;

    public ControlPanel(ControlerEvents event) {
        this.event = event;
        try {
            time = new JFormattedTextField(new MaskFormatter("####"));
            time.setText("100");
            time.setColumns(4);
        } catch (ParseException ex) {
            Logger.getLogger(ControlPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        view = new JPanel(new FlowLayout(FlowLayout.LEFT));
        roomBox.setModel(new DefaultComboBoxModel(new String[]{"maps/raum0_beispiel.txt", "maps/raum1.txt", "maps/raum2.txt", "maps/raum3.txt"}));
        roomBox.setSelectedIndex(0);
        paintObstacles.setSelected(true);


        int buttonSize = 40;
        play.setIcon(new ImageIcon(new ImageIcon("icons/play.png").getImage().getScaledInstance(buttonSize, buttonSize, Image.SCALE_SMOOTH)));
        pause.setIcon(new ImageIcon(new ImageIcon("icons/pause.png").getImage().getScaledInstance(buttonSize, buttonSize, Image.SCALE_SMOOTH)));
        stop.setIcon(new ImageIcon(new ImageIcon("icons/stop.png").getImage().getScaledInstance(buttonSize, buttonSize, Image.SCALE_SMOOTH)));
        plus.setIcon(new ImageIcon(new ImageIcon("icons/plus.png").getImage().getScaledInstance(buttonSize, buttonSize, Image.SCALE_SMOOTH)));
        minus.setIcon(new ImageIcon(new ImageIcon("icons/minus.png").getImage().getScaledInstance(buttonSize, buttonSize, Image.SCALE_SMOOTH)));


        play.setBorder(null);
        pause.setBorder(null);
        stop.setBorder(null);
        plus.setBorder(null);
        minus.setBorder(null);
        
        play.setBackground(view.getBackground());
        pause.setBackground(view.getBackground());
        stop.setBackground(view.getBackground());
        plus.setBackground(view.getBackground());
        minus.setBackground(view.getBackground());


        play.setPreferredSize(new Dimension(buttonSize + (buttonSize / 3), buttonSize));
        pause.setPreferredSize(new Dimension(buttonSize + (buttonSize / 3), buttonSize));
        stop.setPreferredSize(new Dimension(buttonSize + (buttonSize / 3), buttonSize));
        plus.setPreferredSize(new Dimension(buttonSize + (buttonSize / 3), buttonSize));
        minus.setPreferredSize(new Dimension(buttonSize + (buttonSize / 3), buttonSize));


        buildGui();
        buildEvents();
    }

    public void setRoomBoxModel(ComboBoxModel cbm) {
        roomBox.setModel(cbm);
    }

    public void setDriverBoxModel(ComboBoxModel cbm) {
        driverBox.setModel(cbm);
    }

    private void buildGui() {
        
        JPanel labels = new JPanel(new GridLayout(2, 1));
        labels.add(steps);
        labels.add(runTime);
        
        view.add(labels);


        JPanel dropbox = new JPanel(new GridLayout(4, 1));
        dropbox.add(roomLabel);
        dropbox.add(roomBox);
        dropbox.add(driverLabel);
        dropbox.add(driverBox);
        view.add(dropbox);



        JPanel Buttons = new JPanel(new FlowLayout(FlowLayout.LEFT));
        Buttons.add(play);
        Buttons.add(pause);
        Buttons.add(stop);
        Buttons.add(plus);
        Buttons.add(minus);
        Buttons.setPreferredSize(new Dimension(190, 120));
        Buttons.setBorder(BorderFactory.createTitledBorder(new LineBorder(Color.BLACK, 2, true), "Steuerung", TitledBorder.CENTER, TitledBorder.TOP, new Font("Verdana", Font.BOLD, 12), Color.RED));
        view.add(Buttons);



        JPanel Checkbox = new JPanel(new GridLayout(2, 1));
        Checkbox.add(paintSteps);
        Checkbox.add(paintObstacles);

        view.add(Checkbox);
        JPanel timePanel = new JPanel(new GridLayout(1, 3));
        timePanel.add(timeLabel);
        timePanel.add(time);
        timePanel.add(new JLabel("ms"));
        view.add(timePanel);

    }

    private void buildEvents() {
        load.addActionListener(this);
        play.addActionListener(this);
        pause.addActionListener(this);
        stop.addActionListener(this);
        paintSteps.addActionListener(this);
        paintObstacles.addActionListener(this);
        time.addActionListener(this);

        driverBox.addActionListener(this);
        roomBox.addActionListener(this);
        time.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent ke) {
                if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
                    event.refreshWaitTime(Integer.parseInt(time.getText().trim()));
                }
            }
        });

        plus.addActionListener(this);
        minus.addActionListener(this);
    }
long ti=1000;
    public void setSteps(int stepCount) {
        if(ti<1000) ti=1000;
        steps.setText("Schritte: " + stepCount+" - "+(stepCount/(ti/1000)));
    }

    public void setRunTime(long time) {
        ti=time;
        runTime.setText("Zeit: " + msToString(time));
    }

    JPanel getView() {
        return view;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals(load) || e.getSource().equals(roomBox)) {
            ControlPanel.this.event.reloadRoom((String) ControlPanel.this.roomBox.getSelectedItem());
        }
        if (e.getSource().equals(play)) {
            event.startDriver();
        }
        if (e.getSource().equals(pause)) {
            event.pauseDriver();
        }
        if (e.getSource().equals(stop)) {
            event.stopDriver();
        }
        if (e.getSource().equals(paintSteps)) {
            event.getDriver().paintGoneSteps = paintSteps.isSelected();
            event.repaintView();
        }
        if (e.getSource().equals(paintObstacles)) {
            event.getDriver().paintObstacles = paintObstacles.isSelected();
            event.repaintView();
        }
        if (e.getSource().equals(time)) {
            event.refreshWaitTime(Integer.parseInt(time.getText()));
        }

        if (e.getSource().equals(driverBox)) {
            event.setDriver(driverBox.getSelectedItem());
        }

        if (e.getSource().equals(plus)) {
            event.increaseRoomGridSize();
        }
        if (e.getSource().equals(minus)) {
            event.decreaseRoomGridSize();
        }

    }

    public void refreshModel() {
        paintSteps.setSelected(event.getDriver().paintGoneSteps);
        paintObstacles.setSelected(event.getDriver().paintObstacles);
        setDiverLabel(event.getDriver().getName());
        setDriver(event.getDriver());
    }

    public void setDiverLabel(String driverName) {
        driver.setText("Fahrer: " + driverName);
    }

    public void setDriver(DriverInterface driver) {
        if (driver.isStoped()) {
            driverBox.setSelectedItem(driver);
        }
    }

    public void setDriverChangeState(boolean state) {
        driverBox.setEnabled(state);
    }

    public void setLoadRoomState(boolean state) {
        load.setEnabled(state);
        roomBox.setEnabled(state);
    }

    private String msToString(long ms) {
        String re = "";
        long h, m, s, sek=ms/1000,ht,dt,d;
        s = sek % 60;
        m = (sek - s) / 60;
        ht = m % 60;
        h = (m - ht) / 60;
        m = m - (h * 60);
        dt = h % 24;
        d = (h - dt) / 24;
        h -= (d * 24);
        if (d<10) re+="0"+d; else re+=d;
        re+=":";
        if (h<10) re+="0"+h; else re+=h;
        re+=":";
        if (m<10) re+="0"+m; else re+=m;
        re+=":";
        if (s<10) re+="0"+s; else re+=s;
        return re;
    }
}
